extends "res://Prefabs/Character/Map/ActorMap.gd"

export (int) var move_range
export (int) var attack_range

var heroSpawn = Vector2(5,5)
var idle_pos = Vector2(-25,-25)
var move_pos = Vector2(-18,-23)

onready var moveTileContainer = get_parent().get_node("MoveTileContainer")
onready var attackTileContainer = get_parent().get_node("AttackTileContainer")

onready var sprite = $AnimatedSprite
onready var menu = get_parent().get_node("UI/Menu")


func _ready() -> void:
	global_position = Config.size * heroSpawn
	menu.connect("move_click",self,"showMovePath")
	menu.connect("wait_click",self,"playerChangeToGray")
	menu.connect("attack_click",self,"showAttackPath")
	
func _on_Swordmaster_input_event(viewport: Node, event: InputEvent, shape_idx: int) -> void:
	if event is InputEventMouseButton && event.button_index == BUTTON_LEFT && event.is_pressed():
		#弹出菜单
		if Game.game_state == Game.GAMESTATE.IDLE:
			Game.current_player = self
			Game.game_state = Game.GAMESTATE.SHOWMENU
			menu.set_pos(global_position+Vector2(16,-16))

func start_move():
	movePath = AStarPath._get_path(heroSpawn,Game.mouse_pos)
	movePoint = movePath.pop_front()
	Game.game_state = Game.GAMESTATE.MOVEING
		
#人物移动	
func _physics_process(delta):
	if movePoint != Vector2.ZERO and Game.mouse_pos != heroSpawn:
		var dir = global_position.direction_to(movePoint*Config.size)
		velocity = dir * speed
		
		if Game.game_state == Game.GAMESTATE.MOVEING:
			setActorAnim(dir,sprite,move_pos,idle_pos)
		
		if global_position.distance_to(movePoint*Config.size) <= 2:
			#到达数组的一个点
			global_position = movePoint * Config.size
			if !movePath.size():
				if !isArrive:
					#到达数组最后一个点
					cleanPath()
					heroSpawn = Game.mouse_pos
					setActorAnim(Vector2(0,0),sprite,move_pos,idle_pos)
					#menu.ctrl_move_btn(false)
					yield(get_tree().create_timer(0.2), "timeout")
					menu.ctrl_menu(true)
					menu.set_pos(global_position + Vector2(16,-16))
					isArrive = true
				return 
			else :
				movePoint = movePath.pop_front()
		else :
			isArrive = false
			global_position += velocity*delta

func cleanPath():
	cleanActorPath(moveTileContainer,attackTileContainer)

func showMovePath():
	if Game.current_player.heroSpawn == heroSpawn:
		showActorMovePath(moveTileContainer,heroSpawn,move_range)

func showAttackPath():
	if Game.current_player.heroSpawn == heroSpawn:
		showActorAttackPath(attackTileContainer,heroSpawn,attack_range)
		
func playerChangeToGray():
	if Game.current_player.heroSpawn == heroSpawn:
		setActorAnim(Vector2(-1,-1),Game.current_player.get_node("AnimatedSprite"),move_pos,idle_pos)
	
func enter_fight_scene():
	Utils.getSceneManager().enter_fight_scene()
